package com.example.serialportdemo;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class TestActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText editText;
    private Button button;
    private TextView textView;
    private IBinder mIBinder;
    private ServiceConnection UserConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mIBinder = iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mIBinder = null;

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initService();
    }

    private void initService() {
        Intent service = new Intent(this,IPCService.class);
        bindService(service,UserConnection, BIND_AUTO_CREATE);
        button.setOnClickListener(this::onClick);
    }

    private void initViews() {
        editText = findViewById(R.id.edit_num);
        button = findViewById(R.id.btn_query);
        textView = findViewById(R.id.tv_result);
    }

    @Override
    public void onClick(View view) {
        int num = Integer.parseInt(editText.getText().toString());
        if(mIBinder == null){
            Toast.makeText(TestActivity.this,"未连接服务器",Toast.LENGTH_SHORT).show();
        }else {
            android.os.Parcel _data = android.os.Parcel.obtain();
            android.os.Parcel _reply = android.os.Parcel.obtain();
            String _result = null;
            try {
                _data.writeInterfaceToken("IPCService");
                _data.writeInt(num);
                _data.writeInt(4);
                mIBinder.transact(0x001,_data,_reply,0);
                _reply.writeNoException();
                _result = _reply.readString();
                String test = _reply.readString();
                int test1 = _reply.readInt();
                Toast.makeText(TestActivity.this,"我收到的内容是："+ test + "  "+ test1,Toast.LENGTH_SHORT).show();
                textView.setText(_result);
                editText.setText("");

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                _reply.recycle();
                _data.recycle();
            }
        }

    }
}
